using System.Text.RegularExpressions;

namespace AnalyStock.DataManage;

public class JsonDataManage
{
    public static void SaveJosnFileOfSeleStockBySelf(List<SelectStock> seleStockofSelf)
    {
        var tmpListJson = JsonSerializer.Serialize(seleStockofSelf);
        try
        {
            DeleJsonFile(ApplicationParam.SqlDbPath + "SeleStockBySelf.Json");
            FileStream fs = new(ApplicationParam.SqlDbPath + "SeleStockBySelf.Json", FileMode.Create);
            StreamWriter sw = new(fs);
            //开始写入
            sw.Write(Regex.Unescape(tmpListJson)); //反转义字符串转义函数处理JSON数据
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            sw.Dispose();
            fs.Close();
            fs.Dispose();
        }
        catch (Exception e)
        {
            e.Message.ErrorMessage();
        }
    }

    public static List<SelectStock> ReadJsonFileOfSeleStockBySelf()
    {
        List<SelectStock> seleStockofSelf = new();
        try
        {
            if (File.Exists(ApplicationParam.SqlDbPath + "SeleStockBySelf.Json"))
            {
                FileStream fs = new(ApplicationParam.SqlDbPath + "SeleStockBySelf.Json", FileMode.Open);
                StreamReader sr = new(fs);
                //开始写入
                var strJson = sr.ReadToEnd();
                seleStockofSelf = JsonSerializer.Deserialize<List<SelectStock>>(strJson);
                //关闭流
                sr.Close();
                fs.Close();
                sr.Dispose();
                fs.Dispose();
            }
        }
        catch (Exception e)
        {
            e.Message.ErrorMessage();
        }

        return seleStockofSelf;
    }

    public static void SaveFailRecordToJson()
    {
        if (!ErrorLogPool.ErrorLogs.Any())
        {
            return;
        }

        var tmpListJson = JsonSerializer.Serialize(ErrorLogPool.ErrorLogs);
        try
        {
            DeleJsonFile(ApplicationParam.SqlDbPath + "ErrorLogs.Json");
            FileStream fs = new(ApplicationParam.SqlDbPath + "ErrorLogs.Json", FileMode.Create);
            StreamWriter sw = new(fs);
            //开始写入
            sw.Write(Regex.Unescape(tmpListJson)); //反转义字符串函数处理JSON数据
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            sw.Dispose();
            fs.Close();
            fs.Dispose();
        }
        catch (Exception e)
        {
            e.Message.ErrorMessage();
        }
    }

    private static void DeleJsonFile(string pathfile)
    {
        try
        {
            if (File.Exists(pathfile))
            {
                File.Delete(pathfile);
            }
        }
        catch (Exception e)
        {
            e.Message.ErrorMessage();
        }
    }
}